package com.dukk.espark.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanUtil<T> implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(BeanUtil.class);
    private static final long serialVersionUID = -1572689026029826417L;

    T t;

    /**
     *  将实体bean String类型且val为null的转换为 ""空字符
     *  解决mongodb在插入 null 字段不存在的问题
     */
    public T BeanValNullToStr(T obj){

        Class class_ = obj.getClass();
        Method[] methods = class_.getMethods();
        Map<String, Method> methodSetMap = new HashMap<>();
        Map<String, Method> methodGetMap = new HashMap<>();
        for(Method method : methods){
            String methodName = method.getName();
            if(methodName.startsWith("set")){
                methodSetMap.put(methodName.replaceFirst("set", "").toUpperCase(), method);
            }
        }

        for(Method method : methods){
            String methodName = method.getName();
            if(methodName.startsWith("get")){
                if(method.getReturnType().getName().toUpperCase().contains("STRING")){
                    try {
                        if(null == method.invoke(obj)){
                            Method methodSet = methodSetMap.get(methodName.replaceFirst("get", "").toUpperCase());
                            methodSet.invoke(obj, "");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return obj;
    }


}
